package com.codeman.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.codeman.business.user.domain.User;
import com.codeman.business.user.domain.UserDetails;
import com.codeman.business.user.mapper.UserMapper;
import com.codeman.business.user.service.IUserService;
import com.codeman.common.constant.UserConstants;
import com.codeman.common.exception.CustomException;
import com.codeman.common.utils.sign.Md5Utils;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 用户Service业务层处理
 * 
 * @author codeman
 * @date 2021-03-24
 */
@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public UserDetails register(User user) {
        //查询用户名是否已注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName());
        int count= this.count(queryWrapper);
        if (count > 0) {
            //用户名已注册
            throw new CustomException(UserConstants.USERNAME_EXIST);
        }
        User entity = new User();
        BeanUtils.copyProperties(user,entity);
        //数据库生成注册记录

        entity.setPassword(Md5Utils.hash(entity.getPassword()));
        this.save(entity);
        //生成UserDetail对象并返回
        UserDetails userDetails = new UserDetails();
        userDetails.setId(entity.getId());
        userDetails.setUsername(entity.getUserName());
        userDetails.setNickName(entity.getNickName());
        return userDetails;
    }
    @Override
    public UserDetails login(User user) {
        //根据用户名密码查询记录
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUserName())
                .eq("password",Md5Utils.hash(user.getPassword()));
        List<User> list= this.list(queryWrapper);

        if (list.size() == 0) {
            throw new CustomException("用户不存在/密码错误");
        }
        //生成UserDetail对象并返回
        UserDetails userDetails = new UserDetails();
        user = list.get(0);
        userDetails.setId(user.getId());
        userDetails.setNickName(user.getNickName());
        userDetails.setUsername(user.getUserName());
        return userDetails;
    }
}